﻿using OpenClientX.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Runtime.Serialization.Json;

namespace OpenClientX.Utils
{
    class HttpUtil
    {
        public static UpGradeModel getSysProperty(string key,string url)
        {
            Dictionary<string, string> paramsDic = new Dictionary<string, string>();
            paramsDic.Add("key", key);
            paramsDic.Add("account", "123");
            paramsDic.Add("password", "123");
            paramsDic.Add("func", "keyInfo");
            UpGradeModel versionModel = new UpGradeModel();
            String strResult = "";
            strResult = WebPost(url + "/getOCRTrigger", paramsDic);

            if (strResult.Equals("")) return null;
            var ms1 = new MemoryStream(Encoding.UTF8.GetBytes(strResult));
            {
                DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(UpGradeModel));
                versionModel = (UpGradeModel)deseralizer.ReadObject(ms1);// //反序列化ReadObject
            }
            return versionModel;
        }

        public static string WebPost(string url, Dictionary<string, string> dic)
        {
            #region
            string result = "";
            HttpWebRequest req;
            System.GC.Collect();
            try
            {
                req = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                req.Method = "POST";
                req.Timeout = 30000;
                req.UserAgent = "MSIE; Windows NT 5.1; Windows NT 6.0";
                req.KeepAlive = false;
                System.Net.ServicePointManager.DefaultConnectionLimit = 150;
                req.ContentType = "application/x-www-form-urlencoded";

                //封装参数 -s
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                //封装参数 -e

                req.ContentLength = data.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
            }
            catch (NotSupportedException ex)
            {
                return "netError";
            }
            catch (WebException ex)
            {
                return "netError";
            }
            catch (UriFormatException ex)
            {
                return "urlError";
            }
            try
            {
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容  
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    stream.Close();
                }
            }
            catch (Exception ex)
            {
                return "";
            }
            return result;
            #endregion
        }

        /// <summary>
        /// 更新客户端post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static String clientPost(string url, Dictionary<string, string> dic)
        {
            #region
            HttpWebRequest req;
            string result = "";
            MemoryStream stream2;
            string tag = "0";
            try
            {
                req = (HttpWebRequest)WebRequest.Create(new Uri(url));
                System.Net.ServicePointManager.DefaultConnectionLimit = 20;
                req.Method = "POST";
                req.Timeout = 20000;
                req.Proxy = null;
                req.KeepAlive = true;
                req.ContentType = "application/x-www-form-urlencoded";
                //封装参数 ---start
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                //封装参数 ---end

                req.ContentLength = data.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    Console.WriteLine("reqStream：" + reqStream.ToString());
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                System.GC.Collect();
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream streamReader = resp.GetResponseStream();
                Console.WriteLine("streamReader：" + streamReader.ToString());
                //获取响应内容  
                using (StreamReader reader = new StreamReader(streamReader, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    byte[] array = Encoding.GetEncoding("iso-8859-1").GetBytes(result);
                    stream2 = new MemoryStream(array);
                    Console.WriteLine("stream2：" + stream2.ToString());
                }
                string filePath = @"C:/MssClientUpGrade/";
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = stream2.Read(buffer, 0, bufferSize);
                if (!Directory.Exists(filePath))//判断文件夹是否存在 filePath为文件保存的路径
                    Directory.CreateDirectory(filePath);//不存在则创建文件夹
                FileStream outputStream = new FileStream(filePath + "OpenClientX.msi", FileMode.CreateNew);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = stream2.Read(buffer, 0, bufferSize);
                }
                stream2.Close();
                outputStream.Close();
                tag = "1";
                return tag;
            }
            catch (Exception ex)
            {
                return tag;
            }
            #endregion
        }

    }
}
